﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using Mammoth.Entities;
using Mammoth.Factories;

namespace Mammoth.Navigations
{
    public class NavigationController : IMammothNavigationService
    {
        Stack<NavigationEntity> stack;
        Panel container;
        NavigationEntity currentView;
        INavigationAnimation animation;
        
        private ITypeFactory viewFactory;

        public NavigationController(Grid container, ITypeFactory viewFactory, INavigationAnimation animation=null)
        {
            this.container = container;
            this.viewFactory = viewFactory;
            if (animation == null)
                this.animation = new FadeInNavigationAnimation();
            stack = new Stack<NavigationEntity>();
        }

        public void NavigateBack()
        {
            if (stack.Count > 0)
            {
                var entity = stack.Pop();
                ShowAnimateCurrentUI(entity.View, entity.Arguments);
            }
        }

        public void SetDefault(Type view, object args = null)
        {
            currentView = new NavigationEntity() { View = view, Arguments = args };

            ShowAnimateCurrentUI(view, args);
        }

        public void Show(Type view, object arguments = null)
        {
            if (currentView.GetType() == view) return;

            stack.Push(currentView);
            currentView = new NavigationEntity() { View = view, Arguments = arguments };

            ShowAnimateCurrentUI(view, arguments);
        }

        private void ShowAnimateCurrentUI(Type view, object arguments)
        {
            var viewInstance = (UIElement)viewFactory.CreateByType(view, arguments);

            Storyboard fadeIn = null;

            if (container.Children.Count > 0)
            {
                fadeIn = animation.CreateStoryboard(container.Children[0], 1, 0);
                fadeIn.Completed += (s, e) => RemoveView();
            }

            container.Children.Insert(0, viewInstance);

            if (fadeIn != null)
                fadeIn.Begin();
        }

        private void RemoveView()
        {
            var ch = container.Children[container.Children.Count - 1];
            container.Children.Remove(ch);
        }
    }
}
